import { Injectable } from '@nestjs/common';
import { Platform_Create_Dto, Platform_Update_Dto } from './assets/platform.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Platform } from './assets/platform.entity';
import { Repository } from 'typeorm';
import { Platform_Find_Dto } from './assets/platform.dto';
import {
  util_Db_PageList,
  util_Db_NoPageList,
  util_Db_Add,
  util_Db_Update,
  util_Db_Delete,
} from '@/common/util/db';
import { Platformsort } from '../platformsort/assets/platformsort.entity';
import { Class_Index_ListAll } from '@/common/classes/index';

@Injectable()
export class Platform_Service {
  constructor(
    @InjectRepository(Platform)
    private platform_Repository: Repository<Platform>,
    @InjectRepository(Platformsort)
    private platformSort_Repository: Repository<Platformsort>,
  ) {}

  async platform_Create(data: Platform_Create_Dto) {
    const platformsort = this.platformSort_Repository.create({ id: data.platformsortId });
    return await util_Db_Add({
      createDto: { ...data, platformsort: [platformsort] },
      repository: this.platform_Repository,
    });
  }

  async platform_FindAndProduct() {
    return {
      list: await this.platform_Repository
        .createQueryBuilder('platform')
        .leftJoin('platform.product', 'product')
        .select([
          'platform.id AS platformId',
          'platform.platFormName AS platFormName',
          `JSON_ARRAYAGG(
      JSON_OBJECT("productId", product.id, "name", product.productName)
    ) AS products`,
        ])
        .groupBy('platform.id')
        .getRawMany(),
    };
  }

  async platform_FindByPage(data: Platform_Find_Dto) {
    return await util_Db_PageList<Platform>({
      queryBuilder: this.platform_Repository
        .createQueryBuilder('platform')
        .leftJoinAndSelect('platform.platformsort', 'platformsort'),
      query: {
        'platform.isRecommod': data.isRecommod,
        'platform.platFormName': data.platFormName,
        'platform.id': data.platformsortId,
        size: data.size,
        page: data.page,
      },
    });
  }

  async platform_GetPlatformWeb() {
    const list = await util_Db_NoPageList<Platform>({
      queryBuilder: this.platform_Repository
        .createQueryBuilder('platform')
        .leftJoinAndSelect('platform.product', 'product')
        .leftJoinAndSelect('platform.platformsort', 'platformsort')
        .where('product.productPrice > 0'),
    });
    const listed = list as unknown as (Platform & {
      platformsortIds: string[];
    })[];
    const platformsort = [];
    listed.forEach((element) => {
      let hasSell: string;
      if (element.hasSell < 1000) hasSell = '100加';
      if (element.hasSell > 1000 && element.hasSell < 10000) hasSell = '1000加';
      if (element.hasSell > 10000) hasSell = '10000加';
      element.hasSell = hasSell as any;
      element.platformsort.forEach((item) => {
        platformsort.push(item.id);
      });
      element.tags = JSON.parse(element.tags);
      element.platformsortIds = platformsort;
      delete element.platformsort;
      delete element.status;
    });
    const listedFinally = listed.filter((item) => {
      return item.product.length > 0;
    });
    return listedFinally;
  }

  async platform_FindAllSelect(): Promise<Class_Index_ListAll> {
    return (await util_Db_NoPageList<Platform>({
      queryBuilder: this.platform_Repository
        .createQueryBuilder('platform')
        .select(['platform.id AS id', 'platform.platFormName AS name']),
      isRaw: true,
    })) as unknown as Class_Index_ListAll;
  }

  async platform_FindOneById(id: number) {
    return await this.platform_Repository
      .createQueryBuilder('platform')
      .andWhere(`platform.id = :id`, { id: id })
      .getOne();
  }

  async platform_Update(body: Platform_Update_Dto) {
    const platformsort = this.platformSort_Repository.create({ id: body.platformsortId });
    return await util_Db_Update({
      findOne: () => this.platform_FindOneById(body.id),
      updateDto: { ...body, platformsort: [platformsort] },
      repository: this.platform_Repository,
    });
  }

  async platform_Remove(id: number) {
    return await util_Db_Delete({
      findOne: () => this.platform_FindOneById(id),
      id,
      repository: this.platform_Repository,
    });
  }
}
